package com.thl.thl_advertlibrary.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.thl.thl_advertlibrary.R;

import java.text.MessageFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Author：CL
 * 日期:2021/7/27
 * 说明：用户协议记录
 **/
public class UserAgreementHelper {
    public static final String IS_ACCEPT_AGREEMENT = "is_accept_agreement";

    public static boolean isAcceptedUserAgreement(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getBoolean(IS_ACCEPT_AGREEMENT, false);
    }

    public static void setAcceptedUserAgreementState(Context context, boolean accepted) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        preferences.edit().putBoolean(IS_ACCEPT_AGREEMENT, accepted).apply();
    }


    /**
     * 撤销用户协议同意授权
     *
     * @param context
     */
    public static void revokeUserAgreementAuthorize(@NonNull Activity context) {
        revokeUserAgreementAuthorize(context, Gravity.BOTTOM);
    }

    /**
     * 撤销用户协议同意授权
     *
     * @param context
     */
    public static void revokeUserAgreementAuthorize(@NonNull Activity context, int gravity) {
        showOkCancelDialog(context, "撤回同意", context.getString(R.string.fhad_revoke_agreement_1), "取消", "确定", true, gravity, new OnDialogClickListener() {
            @Override
            public void onConfirmClick(Dialog dialog) {
                showOkCancelDialog(context, "无法继续使用应用", context.getString(R.string.fhad_revoke_agreement_2), "取消", "确定", false, gravity, new OnDialogClickListener() {
                    @Override
                    public void onConfirmClick(Dialog dialog) {
                        @SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, Boolean> asyncTask = new AsyncTask<Void, Void, Boolean>() {
                            ProgressDialog loadingDialog;

                            @Override
                            protected Boolean doInBackground(Void... voids) {
                                try {
                                    Thread.sleep(1000 * 3);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                return clearApplicationUserData(context);
                            }


                            @Override
                            protected void onPreExecute() {
                                Log.d("XXX", " onPreExecute~~~~");
                                loadingDialog = new ProgressDialog(context);
                                loadingDialog.setMessage("清除中，请稍后。。。");
                                loadingDialog.show();
                                context.findViewById(android.R.id.content).postDelayed(() -> {
                                    if (loadingDialog != null && loadingDialog.isShowing()) {
                                        loadingDialog.dismiss();
                                        loadingDialog = null;
                                    }
                                    Toast.makeText(context, "已清除用户数据", Toast.LENGTH_SHORT).show();
                                }, 1000 * 2);
                            }

                            @Override
                            protected void onPostExecute(Boolean aBoolean) {
                                Log.d("XXX", " onPostExecute：" + aBoolean);
                                if (loadingDialog != null && loadingDialog.isShowing()) {
                                    loadingDialog.dismiss();
                                    loadingDialog = null;
                                }
                            }

                        };
                        asyncTask.execute();

                    }

                    @Override
                    public void onCancelClick(Dialog dialog) {

                    }
                });
            }

            @Override
            public void onCancelClick(Dialog dialog) {

            }
        });

    }

    public interface OnDialogClickListener {
        void onConfirmClick(Dialog dialog);

        void onCancelClick(Dialog dialog);
    }

    public static void showOkCancelDialog(Activity activity, String title, String message, String cancelStr, String okStr, boolean startTimer, int gravity, OnDialogClickListener listener) {
        Dialog dialog = new Dialog(activity, R.style.CustomBottomDialog);
        View view = LayoutInflater.from(activity).inflate(R.layout.fhad_ok_cancel_dialog, null);
        view.setBackgroundResource(gravity == Gravity.CENTER ? R.drawable.center_dialog_bg : R.drawable.bottom_dialog_bg);


        dialog.setContentView(view);
        dialog.setCancelable(false);
        TextView tvTitle = view.findViewById(R.id.fhad_tv_title);
        TextView tvContent = view.findViewById(R.id.fhad_tv_content);
        TextView tvConfirm = view.findViewById(R.id.fhad_tv_confirm);
        TextView tvCancel = view.findViewById(R.id.fhad_tv_cancel);
        tvConfirm.findViewById(R.id.fhad_tv_confirm)
                .setOnClickListener(v -> {
                    dialog.dismiss();
                    if (listener != null) {
                        listener.onConfirmClick(dialog);
                    }
                });

        tvCancel
                .setOnClickListener(v -> {
                    dialog.dismiss();
                    if (listener != null) {
                        listener.onCancelClick(dialog);
                    }
                });

        tvTitle.setText(title);
        tvContent.setText(message);
        tvConfirm.setText(okStr);
        tvCancel.setText(cancelStr);

        Window window = dialog.getWindow();
        window.setGravity(gravity);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);

        if (gravity == Gravity.CENTER) {
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
            int margin = dip2px(activity, 25);
            layoutParams.leftMargin = margin;
            layoutParams.rightMargin = margin;
            view.setLayoutParams(layoutParams);
        }

        dialog.show();

        if (startTimer) {
            tvConfirm.setEnabled(false);
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                private int count = 10;

                @Override
                public void run() {
                    if (activity.isFinishing() || activity.isDestroyed()) {
                        timer.cancel();
                        return;
                    }
                    tvConfirm.post(() -> {
                        if (count > 0) {
                            tvConfirm.setText(MessageFormat.format("{0}'('{1}')'", okStr, count--));
                        } else {
                            timer.cancel();
                            tvConfirm.setText(okStr);
                            tvConfirm.setEnabled(true);
                        }
                    });

                }
            }, 0, 1000);
        }

    }

    private static int dip2px(Context context, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
    }

    public static boolean clearApplicationUserData(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        return activityManager.clearApplicationUserData();
    }
}
